import Input from '@/component/Input'
import NavBar from '@/component/Nav'
import { useFormik } from 'formik'
import styles from './index.module.scss'
import * as Yup from 'yup'
import { useDispatch } from 'react-redux'
import { AuthorizationsFn, sendCodeRegxFn } from '@/store/action/user'
import { Toast } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useHistory, useLocation } from 'react-router'
export default function Login() {
  const dispatch = useDispatch()
  const [time, setTime] = useState(0)
  const timeID = useRef(1)
  const history = useHistory()
  const location = useLocation<{ from: string }>()

  type propsValus = {
    mobile: string
    code: string
  }
  const formik = useFormik({
    initialValues: {
      mobile: '13802409362',
      code: '246810',
    } as propsValus,
    onSubmit: async (values) => {
      await dispatch(AuthorizationsFn(values))
      // 提示用户
      Toast.show({ content: '登录成功' })

      const redictPath = location.state ? location.state.from : '/'

      // 跳转到首页
      history.push(redictPath)
    },

    // 校验
    // validate: (value) => {
    //   // // const valRegx = {} as propsValus
    //   // const phoneNum =
    //   //   /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
    //   // const codeReg = /^\d{6}$/
    //   // // 校验手机
    //   // if (!phoneNum.test(value.mobile)) {
    //   //   valRegx.mobile = '手机校验不通过'
    //   // }
    //   // // 校验短信
    //   // if (!codeReg.test(value.code)) {
    //   //   valRegx.code = '短信校验不通过'
    //   // }
    //   // return valRegx
    //   // 表单验证
    //   // 表单验证
    //   // 表单验证
    // },

    validationSchema: Yup.object().shape({
      // 手机号验证规则
      mobile: Yup.string()
        .required('请输入手机号')
        .matches(/^1[3456789]\d{9}$/, '手机号格式错误'),

      // 手机验证码验证规则
      code: Yup.string()
        .required('请输入验证码')
        .matches(/^\d{6}$/, '验证码6个数字'),
    }),
  })
  // 发送短信验证
  const handleSendcodeFn = async () => {
    // 定时器还在执行，直接退出
    if (time > 0) return
    // 如果校验不通过提示用户
    if (formik.errors.mobile) {
      return Toast.show({ content: formik.errors.mobile })
    }
    // 提交到dispatch
    await dispatch(sendCodeRegxFn(formik.values.mobile))
    // 发送成功
    Toast.show({ content: '验证码发送成功' })
    // 设置数值
    setTime(60)
    //  开启定时器
    timeID.current = window.setInterval(() => {
      // 在useState中的setTime清理定时器
      setTime((time) => {
        if (time === 1) clearInterval(timeID.current)
        return time - 1
      })
    }, 1000)
  }
  useEffect(() => {
    return () => {
      clearInterval(timeID.current)
    }
  }, [])
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <Input
            className="input"
            name="mobile"
            placeholder="请输入手机号"
            autoComplete="off"
            Errmsg={formik.touched.mobile ? formik.errors.mobile : ''}
            value={formik.values.mobile}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          ></Input>
          {/* 短信验证码输入框 */}
          <Input
            Errmsg={formik.touched.code ? formik.errors.code : ''}
            className="input"
            name="code"
            placeholder="请输入验证码"
            maxLength={6}
            autoComplete="off"
            extra={<span onClick={handleSendcodeFn}>{time === 0 ? '发送验证码' : `请${time}再尝试`}</span>}
            value={formik.values.code}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          ></Input>
          {/* 登录按钮 */}
          <button type="submit" className="login-btn" disabled={!formik.isValid}>
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
